package com.jiazhong.example.project.shoppingcart.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

// 生成验证码的图片
@WebServlet("/verification_code")
public class VerificationCodeController extends BaseController {

    private String code = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("请求了验证码");
        // 1.产生一张图片
        BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
        // 2.产生一支笔
        Graphics g = image.getGraphics();
        // 3.填充背景色
        g.setColor(Color.GRAY);
        g.fillRect(0, 0, 100, 30);
        // 4.书写内容（生成4个字符）
        StringBuilder content = new StringBuilder();
        int x = 10, y = 15;
        for (int i = 0; i < 4; i++) {
            int index = (int) (Math.random() * code.length());
            String a = code.charAt(index) + "";
            content.append(a);
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            Color color = new Color(red, green, blue);
            g.setColor(color);
            g.drawString(a, x, y);
            x += 20;
        }
        // 5.将验证码存放到session中
        request.getSession().setAttribute("yzm_code", content.toString());
        // 6.生成这张图片
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        ImageIO.write(image, "JPEG", response.getOutputStream());
        // 7.扔掉这支笔
        g.dispose();
    }
}
